package com.uddenberg.wt;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import com.uddenberg.wt.containers.RecordContainer;
import com.uddenberg.wt.containers.RecordContainer.RecordTypes;
import com.uddenberg.wt.dbdefinitions.DailyDataDefinition.DailyDataColumns;
import com.uddenberg.wt.dbdefinitions.FoodMealDataDefinition.FoodMealDataColumns;
import com.uddenberg.wt.dbdefinitions.FoodOtherDataDefinition.FoodOtherDataColumns;
import com.uddenberg.wt.dbdefinitions.GeneralDataDefinition.GeneralDataColumns;
import com.uddenberg.wt.helpers.GeneralHelper;

import android.app.ActivityGroup;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class RecordsActivity extends ActivityGroup {
	
	private ProgressDialog mProgressDialog = null; 
    private ArrayList<RecordContainer> mOrders = null;
    private RecordAdapter mAdapter;
    private Runnable viewRecords;
	private ListView mList;
	private Spinner mFilter;
	private Cursor cursor;
	private Button btnFilter;
	private int mCurrentFilter = 0;
	private Intent intent;
	private static final int FILTER_NONE = 0;
	private static final int FILTER_GENERAL = 1;
	private static final int FILTER_DAILY = 2;
	private static final int FILTER_FOOD_MEAL = 3;
	private static final int FILTER_FOOD_OTHER = 4;
    
	private static final String[] GENERAL_PROJECTION = new String[] {
        GeneralDataColumns._ID, // 0
        GeneralDataColumns.TIME, // 1
    };
	private static final String[] DAILY_PROJECTION = new String[] {
        DailyDataColumns._ID, // 0
        DailyDataColumns.DATE, // 1
    };
	private static final String[] FOOD_MEAL_PROJECTION = new String[] {
        FoodMealDataColumns._ID, // 0
        FoodMealDataColumns.DATE, // 1
    };
	private static final String[] FOOD_OTHER_PROJECTION = new String[] {
		FoodOtherDataColumns._ID, // 0
		FoodOtherDataColumns.DATE, // 1
    };

    private Runnable returnRes = new Runnable() {
        public void run() {
        	mAdapter.clear();
        	mAdapter.notifyDataSetChanged();
            if(mOrders != null && mOrders.size() > 0){
                mAdapter.notifyDataSetChanged();
                for(int i=0;i<mOrders.size();i++) {
                	mAdapter.add(mOrders.get(i));
                }
            }
            mProgressDialog.dismiss();
            mAdapter.notifyDataSetChanged();
        }
    };
    
    private void deleteRecord(int type, long id) {
    	Uri deleteUri = null;
    	switch(type) {
    	case RecordTypes.GENERAL:
    		deleteUri = ContentUris.withAppendedId(GeneralDataColumns.CONTENT_URI, id);
    		break;
    	case RecordTypes.DAILY:
    		deleteUri = ContentUris.withAppendedId(DailyDataColumns.CONTENT_URI, id);
    		break;
    	case RecordTypes.FOOD_MEAL:
    		deleteUri = ContentUris.withAppendedId(FoodMealDataColumns.CONTENT_URI, id);
    		break;
    	case RecordTypes.FOOD_OTHER:
    		deleteUri = ContentUris.withAppendedId(FoodOtherDataColumns.CONTENT_URI, id);
    		break;
    	}
    	//Log.w("URI:",deleteUri.toString());
    	getContentResolver().delete(deleteUri, null, null);
    	 
    }
    
    private void getRecords(){
    	try{
    		mOrders = new ArrayList<RecordContainer>();
    		
    		switch(mCurrentFilter) {
    			case FILTER_GENERAL:
    				addRecord(FILTER_GENERAL, 0);
    				break;
    			
    			case FILTER_DAILY:
    				addRecord(FILTER_DAILY, 0);
    				break;
    				
    			case FILTER_FOOD_MEAL:
    				addRecord(FILTER_FOOD_MEAL, 0);
    				break;
				
    			case FILTER_FOOD_OTHER:
    				addRecord(FILTER_FOOD_OTHER, 0);
    				break;
    				
    			case FILTER_NONE:
    				addRecord(FILTER_GENERAL, 5);
    				addRecord(FILTER_DAILY, 5);
    				addRecord(FILTER_FOOD_MEAL, 5);
    				addRecord(FILTER_FOOD_OTHER, 5);
    				break;
    		}
            Thread.sleep(1000);
          } catch (Exception e) { 
            Log.e("BACKGROUND_PROC", e.getMessage());
          }
          runOnUiThread(returnRes);
      }
    
    private void addRecord(int filter, int limit) {
    	int type = 0;
    	switch(filter) {
    		case FILTER_GENERAL:
    			intent.setData(GeneralDataColumns.CONTENT_URI);
    			cursor = managedQuery(getIntent().getData(), GENERAL_PROJECTION, null, null,
    	                GeneralDataColumns.DEFAULT_SORT_ORDER);
    			type = RecordTypes.GENERAL;
    		break;
    		
    		case FILTER_DAILY:
	    		intent.setData(DailyDataColumns.CONTENT_URI);
				cursor = managedQuery(getIntent().getData(), DAILY_PROJECTION, null, null,
						DailyDataColumns.DEFAULT_SORT_ORDER);
				type = RecordTypes.DAILY;
			break;
			
    		case FILTER_FOOD_MEAL:
    			intent.setData(FoodMealDataColumns.CONTENT_URI);
				cursor = managedQuery(getIntent().getData(), FOOD_MEAL_PROJECTION, null, null,
						FoodMealDataColumns.DEFAULT_SORT_ORDER);
    			type = RecordTypes.FOOD_MEAL;
    			break;
    			
    		case FILTER_FOOD_OTHER:
    			intent.setData(FoodOtherDataColumns.CONTENT_URI);
				cursor = managedQuery(FoodOtherDataColumns.CONTENT_URI, FOOD_OTHER_PROJECTION, null, null,
						FoodOtherDataColumns.DEFAULT_SORT_ORDER);
    			type = RecordTypes.FOOD_OTHER;
    			break;
    	}
    	 
    	int count = 0;
		cursor.moveToFirst();
		while (cursor.isAfterLast() == false) {
			RecordContainer o = new RecordContainer();
			o.setType(type);
			o.setDate(cursor.getInt(1));
			o.setId(cursor.getInt(0));
			mOrders.add(o);
			count++;
			if(limit > 0) {
				if(count == limit) {
					break;
				}
			}
			cursor.moveToNext();
			
		}
    	
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem aItem) {
         AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) aItem.getMenuInfo();

         /* Switch on the ID of the item, to get what the user selected. */
         switch (aItem.getItemId()) {
              case 0:
            	  
            	  RecordContainer c = this.mAdapter.getItem(menuInfo.position);
            	  //Log.w("Info: ", "Id: " + c.getId() +", Type: " + c.getType());
            	  deleteRecord(c.getType(), (long)c.getId());
            	  populateList();
            	  return true; /* true means: "we handled the event". */
         } 

         return false;
    }
    

    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.layout.menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.icontext: Toast.makeText(this, "You pressed the icon and text!", Toast.LENGTH_LONG).show();
	                            break;
	    }
	    return true;
	}
    
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.records);
        
        // If no data was given in the intent (because we were started
        // as a MAIN activity), then use our default content provider.
        intent = getIntent();
        
        
        
        mList = (ListView)findViewById(R.id.records_listview);
        mList.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
        	 
			public void onCreateContextMenu(ContextMenu menu, View v,
					ContextMenuInfo menuInfo) {
				menu.setHeaderTitle("Choose alternative");
				menu.add(0, 0, 0, "Delete this record");
				
			}
        });
        
        mOrders = new ArrayList<RecordContainer>();
        
        this.mAdapter = new RecordAdapter(this.getParent(), R.layout.records_listitem, mOrders);
        mList.setAdapter(this.mAdapter);
        
        viewRecords = new Runnable(){
            public void run() {
                getRecords();
            }
        };
          
        mFilter = (Spinner) findViewById(R.id.records_spinner_filter);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
        		this.getParent(), R.array.filter_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mFilter.setAdapter(adapter);
        mFilter.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                Object item = parent.getItemAtPosition(pos);
                
                if (String.valueOf(item).equals("Show all")) {
                	mCurrentFilter = FILTER_NONE;
                } else if (String.valueOf(item).equals("General records")) {
                	mCurrentFilter = FILTER_GENERAL;
                } else if (String.valueOf(item).equals("Daily records")) {
                	mCurrentFilter = FILTER_DAILY;
                } else if (String.valueOf(item).equals("Food meal records")) {
                	mCurrentFilter = FILTER_FOOD_MEAL;
                } else if (String.valueOf(item).equals("Food other records")) {
                	mCurrentFilter = FILTER_FOOD_OTHER;
                }
                
            }
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        
        
        
        populateList();
        
        
        btnFilter = (Button)findViewById(R.id.records_btn_filter);
        btnFilter.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
				populateList();
			}
		});
        
        
        
        
    }
    
    private void populateList() {
    	Thread thread =  new Thread(null, viewRecords, "MagentoBackground");
        thread.start();
        mProgressDialog = ProgressDialog.show(RecordsActivity.this,    
              "Please wait...", "Retrieving data ...", true);
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    private class RecordAdapter extends ArrayAdapter<RecordContainer> {

        private ArrayList<RecordContainer> items;
        private Context ctx;

        public RecordContainer getItem(int position) {
        	return this.items.get(position);
        }
        
        
        public RecordAdapter(Context context, int textViewResourceId, ArrayList<RecordContainer> items) {
                super(context, textViewResourceId, items);
                this.ctx = context;
                this.items = items;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                View view = convertView;
                
                
                if (view == null) {
                    LayoutInflater vi = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    view = vi.inflate(R.layout.records_listitem, null);
                }
                final RecordContainer item = items.get(position);
                if (item != null) {
                	TextView date = (TextView) view.findViewById(R.id.records_listitem_date);
                	TextView text = (TextView) view.findViewById(R.id.records_listitem_text);
                	
                	final Calendar cal = Calendar.getInstance();
                	cal.setTimeInMillis((long)item.getDate()*1000);
                	date.setText(
                			DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault())
                			.format(cal.getTime())+" "+GeneralHelper.pad(cal.get(Calendar.HOUR_OF_DAY))+":"+GeneralHelper.pad(cal.get(Calendar.MINUTE)));    
                	String type = "";
                	switch (item.getType()) {
	                	case RecordTypes.GENERAL:
	                		type = "General";
	                		text.setTextColor(Color.parseColor("#FF470A"));
	                		break;
	                	case RecordTypes.DAILY:
	                		type = "Daily";
	                		text.setTextColor(Color.parseColor("#E0E0E0"));
	                		break;
	                	case RecordTypes.FOOD_MEAL:
	                		type = "Food, meal";
	                		text.setTextColor(Color.parseColor("#CC9900"));
	                		break;
	                	case RecordTypes.FOOD_OTHER:
	                		type = "Food, other";
	                		text.setTextColor(Color.parseColor("#00CC99"));
	                		break;
                	}
                	text.setText(type);
                	
                }
                return view;
        }
}
}
